package xian.woniu.service.impl;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xian.woniu.entity.Appointment;
import xian.woniu.entity.Patient;
import xian.woniu.mapper.AppointmentMapper;
import xian.woniu.mapper.custom.CustomAppointmentMapper;
import xian.woniu.service.IAppointmentService;
import xian.woniu.service.IPatientService;
import xian.woniu.util.ResultVO;

import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @author SongHang
 * @time 2022/06/30 15:10:50
 */
@Service
@Transactional
@Slf4j
public class AppointmentServiceImpl implements IAppointmentService {
    private CustomAppointmentMapper appointmentMapper;
    /**
     * Feign调用需要
     */
    private IPatientService patientService;

    public AppointmentServiceImpl(CustomAppointmentMapper appointmentMapper, IPatientService patientService) {
        this.appointmentMapper = appointmentMapper;
        this.patientService = patientService;
    }

    @Override
    public int save(Appointment appointment) {
        return appointmentMapper.insertSelective(appointment);
    }

    @Override
    public int delete(Integer aid) {
        return appointmentMapper.deleteByPrimaryKey(aid);
    }

    @Override
    public Appointment findOne(Integer aid) {
        return appointmentMapper.selectByPrimaryKey(aid);
    }

    @Override
    public List<Appointment> findAll() {
        return appointmentMapper.selectByExample(null);
    }

    @Override
    public int update(Appointment appointment) {
        return appointmentMapper.updateByPrimaryKeySelective(appointment);
    }

    @Override
    public List<Appointment> findAllWithMsg() {
        List<Appointment> all = appointmentMapper.findAllWithMsg();
        for (Appointment appointment : all) {
            Integer pid = appointment.getPid();
            ResultVO one = patientService.findOne(String.valueOf(pid));

//            注意回传回来的数据是Object对象 得处理，还得再转为对象
            Map map = (Map) one.getData();
            System.out.println(map);
            Patient patient = new Patient();
            try {
                BeanUtils.populate(patient, map);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            appointment.setPatient(patient);
        }
        return all;
    }
}
